package com.tbl.modules.wms2.controller.purchasein;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.plugins.Page;
import com.tbl.common.exception.RRException;
import com.tbl.modules.platform.controller.AbstractController;
import com.tbl.modules.platform.service.system.RoleService;
import com.tbl.modules.wms.dao.baseinfo.WarehouseDAO;
import com.tbl.modules.wms.entity.baseinfo.Warehouse;
import com.tbl.modules.wms2.dao.purchasein.PurchaseOrderDAO;
import com.tbl.modules.wms2.entity.operation.YclInOutFlowEntity;
import com.tbl.modules.wms2.entity.ordermanage.delivery.DeliveryEntity;
import com.tbl.modules.wms2.entity.purchasein.PurchaseOrderSaveEntity;
import com.tbl.modules.wms2.entity.purchasein.YclPurchaseCorrectDTO;
import com.tbl.modules.wms2.entity.purchasein.YclPurchaseCorrectEntity;
import com.tbl.modules.wms2.entity.purchasein.YclPurchaseCorrectSubDTO;
import com.tbl.modules.wms2.entity.report.YclInventoryEntity;
import com.tbl.modules.wms2.entity.report.YclInventoryUpdateDTO;
import com.tbl.modules.wms2.service.common.CountService;
import com.tbl.modules.wms2.service.operation.YclInOutFlowService;
import com.tbl.modules.wms2.service.ordermanage.delivery.DeliveryService;
import com.tbl.modules.wms2.service.purchasein.PurchaseCorrectService;
import com.tbl.modules.wms2.service.report.InventoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 采购更正
 *
 * @author DASH
 */
@Controller
@RequestMapping(value = "/ycl/purchaseIn/PurchaseCorrect")
public class PurchaseCorrectController extends AbstractController {

    @Resource
    private RoleService roleService;

    @Resource
    private PurchaseCorrectService purchaseCorrectService;

    @Resource
    private YclInOutFlowService yclInOutFlowService;

    @Resource
    private CountService countService;

    @Resource(name = "yclInventoryService")
    private InventoryService inventoryService;

    @Resource
    DeliveryService deliveryService;

    @Resource
    PurchaseOrderDAO purchaseOrderDAO;

    @Resource
    WarehouseDAO warehouseDAO;

    /**
     * 删除
     *
     * @param
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Map<String, Object> delete(String ids) {
        Map<String, Object> map = new HashMap<>(2);
        boolean result = purchaseCorrectService.delete(ids);
        map.put("result", result);
        map.put("msg", result ? "操作成功！" : "操作失败！");
        return map;
    }

    /**
     * 保存
     *
     * @param
     * @return Map<String, Object>
     */
    @PostMapping(value = "/saveByMap")
    @ResponseBody
    @Transactional
    public Map<String, Object> saveByMap(@RequestBody YclPurchaseCorrectDTO yclPurchaseCorrectDTO) {
        String gzck = countService.getNextCount("GZCK");
        List<YclInOutFlowEntity> sub = yclPurchaseCorrectDTO.getSub();
        sub.stream().forEach(item -> {
            item.setBusinessCode(gzck);
        });
        YclPurchaseCorrectEntity entity = yclPurchaseCorrectDTO.getCorrect();
        entity.setOrderTime(DateUtil.parse(DateUtil.today()));
        entity.setCorrectCode(gzck);
        boolean b = yclInOutFlowService.saveBatch(sub);
        boolean result = purchaseCorrectService.save(entity);
        Map resultMap = new HashMap(2);
        resultMap.put("result", result && b);
        resultMap.put("msg", result && b ? "操作成功！" : "操作失败！");
        return resultMap;
    }

    /**
     * 保存
     *
     * @param
     * @return Map<String, Object>
     */
    @PostMapping(value = "/save")
    @ResponseBody
    public Map<String, Object> save(@RequestBody YclPurchaseCorrectEntity entity) {
        entity.setCorrectCode(countService.getNextCount("GZCK"));
        boolean result = purchaseCorrectService.save(entity);
        Map resultMap = new HashMap(2);
        resultMap.put("result", result);
        resultMap.put("msg", result ? "操作成功！" : "操作失败！");
        return resultMap;
    }

    /**
     * 批量保存
     *
     * @param
     * @return Map<String, Object>
     */
    @PostMapping(value = "/batchSave")
    @ResponseBody
    public Map<String, Object> batchSave(@RequestBody List<YclPurchaseCorrectEntity> entities) {
        entities.stream().forEach(item -> {
            item.setCorrectCode(countService.getNextCount("GZCK"));
        });
        boolean result = purchaseCorrectService.batchSave(entities);
        Map resultMap = new HashMap(2);
        resultMap.put("result", result);
        resultMap.put("msg", result ? "操作成功！" : "操作失败！");
        return resultMap;
    }

    /**
     * 弹出到新增/编辑页面
     *
     * @param id
     * @return ModelAndView
     */
    @RequestMapping(value = "/toEdit")
    @ResponseBody
    public ModelAndView toAdd(String id) {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom2/purchaseIn/purchaseCorrect/edit");
        return mv;
    }

    /**
     * 主表 跳转Grid列表页
     *
     * @return
     */
    @RequestMapping(value = "/toList")
    public ModelAndView toRewindList() {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom2/purchaseIn/purchaseCorrect/list");
        return mv;
    }

    /**
     * 主表-获取Grid列表数据
     *
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/pageView")
    @ResponseBody
    public Map<String, Object> pageView(YclPurchaseCorrectEntity entity) {
        Map<String, Object> paramsMap = getAllParameter();
        Page<YclPurchaseCorrectEntity> mapPage = purchaseCorrectService.getPageList(
                new Page(
                        Integer.parseInt((String) paramsMap.get("page")),
                        Integer.parseInt((String) paramsMap.get("limit"))),
                paramsMap, entity);
        return returnLayResponse(mapPage);
    }

    /**
     * 不分页
     *
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/listView")
    @ResponseBody
    public Map<String, Object> listView(YclPurchaseCorrectEntity entity) {
        List<YclPurchaseCorrectEntity> page = purchaseCorrectService.listView(entity);
        Map<String, Object> map = new HashMap<>(4);
        map.put("code", 0);
        map.put("msg", null);
        map.put("count", 0);
        map.put("data", page);
        return map;
    }

    /**
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/getOut")
    @ResponseBody
    public Map<String, Object> getOut(String poCode) {
        List<Map<String, Object>> out = purchaseCorrectService.getOut(poCode);

//        List<YclPurchaseCorrectEntity> page = purchaseCorrectService.listView(entity);
        Map<String, Object> map = new HashMap<>(4);
        map.put("code", 0);
        map.put("msg", null);
        map.put("count", null);
        map.put("data", out);
        return map;
    }

    /**
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/subOut")
    @ResponseBody
    public Map<String, Object> subOut(@RequestBody List<YclPurchaseCorrectSubDTO> list) {

        Boolean result = true;

        DeliveryEntity deliveryEntity = new DeliveryEntity();

        YclInventoryUpdateDTO yclInventoryUpdateDTO = new YclInventoryUpdateDTO();

        for (YclPurchaseCorrectSubDTO item : list) {

            YclInventoryEntity yclInventoryEntity = inventoryService.find(item.getAreaCode(), item.getStoreCode(), item.getLocatorCode(), item.getMaterialCode(), item.getLotsNum());

            // 有库存
            if (yclInventoryEntity != null) {

                deliveryEntity.setPoCode(item.getPoCode());
                deliveryEntity.setPoLineNum(item.getPoLineNum());
                deliveryEntity.setMaterialCode(item.getMaterialCode());
                deliveryEntity.setLotsNum(item.getLotsNum());
                deliveryEntity.setEntityId(item.getAreaCode());
                DeliveryEntity deliveryServiceOne = deliveryService.getOne(deliveryEntity);

                Map map = new HashMap(2);
                map.put("rcvLineId", Long.parseLong(deliveryServiceOne.getEbsLineId()));
                map.put("quantity", Double.parseDouble(String.valueOf(item.getCorrectQuantity())));
                purchaseOrderDAO.returnPurchaseOrder(map);

                // TODO
                if ("S".equals((String) map.get("retCode"))) {

                    yclInventoryUpdateDTO.setAreaCode(item.getAreaCode());
                    yclInventoryUpdateDTO.setStoreCode(item.getStoreCode());
                    yclInventoryUpdateDTO.setMaterialCode(item.getMaterialCode());
                    yclInventoryUpdateDTO.setLocatorCode(item.getLocatorCode());
                    yclInventoryUpdateDTO.setLotsNum(item.getLotsNum());
                    yclInventoryUpdateDTO.setAmount(item.getCorrectQuantity());
                    yclInventoryUpdateDTO.setInout("0");
                    inventoryService.updateInventory(yclInventoryUpdateDTO);

                } else if ("E".equals((String) map.get("retCode"))) {
                    result = false;
                }

            } else {

                yclInventoryUpdateDTO.setAreaCode(item.getAreaCode());
                yclInventoryUpdateDTO.setStoreCode(item.getStoreCode());
                yclInventoryUpdateDTO.setMaterialCode(item.getMaterialCode());
                yclInventoryUpdateDTO.setLocatorCode(item.getLocatorCode());
                yclInventoryUpdateDTO.setLotsNum(item.getLotsNum());
                yclInventoryUpdateDTO.setAmount(item.getCorrectQuantity());
                yclInventoryUpdateDTO.setInout("0");
                inventoryService.updateInventory(yclInventoryUpdateDTO);
            }

            // 保存更正
            YclPurchaseCorrectEntity purchaseCorrectEntity = new YclPurchaseCorrectEntity();
            BeanUtils.copyProperties(item, purchaseCorrectEntity);
            purchaseCorrectEntity.setSupplierName(item.getVendorName());
            purchaseCorrectEntity.setOrderTime(item.getCreateTime());
            purchaseCorrectEntity.setCorrectCode(countService.getNextCount("GZCK"));
            purchaseCorrectEntity.setCreateTime(DateUtil.date());
            purchaseCorrectService.save(purchaseCorrectEntity);

        }

        Map resultMap = new HashMap(2);
        resultMap.put("result", result);
        resultMap.put("msg", result ? "操作成功！" : "操作失败！");
        return resultMap;
    }


    /**
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/subIn")
    @ResponseBody
    public Map<String, Object> subIn(@RequestBody List<YclPurchaseCorrectSubDTO> list) {

        Boolean result = true;

        for (YclPurchaseCorrectSubDTO yclPurchaseCorrectSubDTO : list) {

            // TODO 更新EBS库存
            Map map = new HashMap(1);
            map.put("code", yclPurchaseCorrectSubDTO.getStoreCode());
            map.put("entityId", yclPurchaseCorrectSubDTO.getAreaCode());
            Warehouse warehouseByCode = warehouseDAO.getWarehouseByCode(map);
            PurchaseOrderSaveEntity purchaseOrderSaveEntity = new PurchaseOrderSaveEntity();
            purchaseOrderSaveEntity.setPoLineId(Long.valueOf(yclPurchaseCorrectSubDTO.getPoLineId()));
            purchaseOrderSaveEntity.setLoctorId(warehouseByCode.getLocatorId());
            purchaseOrderSaveEntity.setSubCode(yclPurchaseCorrectSubDTO.getStoreCode());
            purchaseOrderSaveEntity.setTransDate(new Timestamp(System.currentTimeMillis()));
            purchaseOrderSaveEntity.setVendorLot(yclPurchaseCorrectSubDTO.getLotsNum());
            purchaseOrderSaveEntity.setSourceId(yclPurchaseCorrectSubDTO.getPoLineId());
            purchaseOrderSaveEntity.setQuantity(Double.valueOf(String.valueOf(yclPurchaseCorrectSubDTO.getCorrectQuantity())));
            purchaseOrderDAO.savePurchaseOrder(purchaseOrderSaveEntity);

            // TODO
            if ("S".equals(purchaseOrderSaveEntity.getRetCode())) {
                Long rcvLineId = purchaseOrderSaveEntity.getRcvLineId();

                // update kc
                YclInventoryUpdateDTO yclInventoryUpdateDTO = new YclInventoryUpdateDTO();
                yclInventoryUpdateDTO.setStoreCode(yclPurchaseCorrectSubDTO.getStoreCode());
                yclInventoryUpdateDTO.setStoreName(yclPurchaseCorrectSubDTO.getStoreName());
                yclInventoryUpdateDTO.setAreaCode(yclPurchaseCorrectSubDTO.getAreaCode());
                yclInventoryUpdateDTO.setAreaName(yclPurchaseCorrectSubDTO.getAreaName());
                yclInventoryUpdateDTO.setLocatorCode(yclPurchaseCorrectSubDTO.getLocatorCode());
                yclInventoryUpdateDTO.setMaterialCode(yclPurchaseCorrectSubDTO.getMaterialCode());
                yclInventoryUpdateDTO.setMaterialName(yclPurchaseCorrectSubDTO.getMaterialName());
                yclInventoryUpdateDTO.setLotsNum(yclPurchaseCorrectSubDTO.getLotsNum());
                yclInventoryUpdateDTO.setAmount(yclPurchaseCorrectSubDTO.getCorrectQuantity());
                yclInventoryUpdateDTO.setInout("1");
                inventoryService.updateInventory(yclInventoryUpdateDTO);

                // 保存更正
                YclPurchaseCorrectEntity purchaseCorrectEntity = new YclPurchaseCorrectEntity();
                BeanUtils.copyProperties(yclPurchaseCorrectSubDTO, purchaseCorrectEntity);
                purchaseCorrectEntity.setSupplierName(yclPurchaseCorrectSubDTO.getVendorName());
                purchaseCorrectEntity.setCorrectCode(countService.getNextCount("GZCK"));
                purchaseCorrectService.save(purchaseCorrectEntity);

            } else if ("E".equals(purchaseOrderSaveEntity.getRetCode())) {
                String retMess = purchaseOrderSaveEntity.getRetMess();
                result = false;
            }
        }
        Map resultMap = new HashMap(2);
        resultMap.put("result", result);
        resultMap.put("msg", result ? "操作成功！" : "操作失败！");
        return resultMap;
    }


    @RequestMapping("/getOneById")
    @ResponseBody
    public YclPurchaseCorrectEntity getOneById(String id) {
        YclPurchaseCorrectEntity byId = purchaseCorrectService.findById(id);
        return byId;
    }

    /**
     * 打印页面
     *
     * @return
     */
    @RequestMapping("/toCorrectPrint")
    @ResponseBody
    public ModelAndView toCorrectPrint() {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom2/purchaseIn/purchaseCorrect/printCorrect");
        return mv;
    }

}
